<template>
  <div class="parking-container">
    <!-- 顶部数据概览 -->
    <div class="overview-section">
      <div class="overview-card available">
        <div class="overview-icon">
          <el-icon><Van /></el-icon>
        </div>
        <div class="overview-content">
          <div class="overview-title">可用车位</div>
          <div class="overview-number">{{ availableSpots.length }}</div>
          <div class="overview-desc">当前空闲车位数量</div>
        </div>
      </div>
      <div class="overview-card my-bookings">
        <div class="overview-icon">
          <el-icon><Tickets /></el-icon>
        </div>
        <div class="overview-content">
          <div class="overview-title">我的预约</div>
          <div class="overview-number">{{ myReservations.length }}</div>
          <div class="overview-desc">当前预约数</div>
        </div>
      </div>
      <div class="overview-card notice">
        <div class="overview-icon">
          <el-icon><Bell /></el-icon>
        </div>
        <div class="overview-content">
          <div class="overview-title">温馨提示</div>
          <div class="overview-desc">预约成功后请按时使用车位</div>
        </div>
      </div>
    </div>

    <!-- 车位列表 -->
    <div class="parking-spots-section">
      <el-card class="spots-card">
        <template #header>
          <div class="card-header">
            <span>车位列表</span>
            <el-radio-group v-model="spotFilter" size="small">
              <el-radio-button label="all">全部车位</el-radio-button>
              <el-radio-button label="available">可用车位</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        
        <el-table :data="paginatedSpots" style="width: 100%" v-loading="loading" stripe>
          <el-table-column prop="spotId" label="车位ID" width="80" />
          <el-table-column prop="spotNumber" label="车位编号" width="120" />
          <el-table-column prop="location" label="位置" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button 
                v-if="scope.row.status === '可用'" 
                type="primary" 
                size="small" 
                @click="showReservationDialog(scope.row)"
              >
                预约
              </el-button>
              <el-button 
                v-else 
                type="info" 
                size="small" 
                disabled
              >
                不可预约
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="spotsCurrentPage"
            :page-size="spotsPageSize"
            :total="filteredSpots.length"
            layout="prev, pager, next, jumper"
            @current-change="handleSpotsPageChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 我的预约记录 -->
    <div class="my-bookings-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>我的预约记录</span>
            <el-button-group>
              <el-button type="primary" plain @click="fetchMyReservations">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </el-button-group>
          </div>
        </template>

        <el-table :data="paginatedReservations" style="width: 100%" v-loading="reservationsLoading" stripe>
          <el-table-column prop="reservationId" label="预约ID" width="80" />
          <el-table-column prop="spotId" label="车位ID" width="80" />
          <el-table-column label="车位信息" min-width="120">
            <template #default="scope">
              <el-popover
                placement="top-start"
                title="车位详情"
                :width="200"
                trigger="hover"
                v-if="scope.row.spotInfo"
              >
                <template #default>
                  <div>
                    <p><strong>车位编号:</strong> {{ scope.row.spotInfo.spotNumber }}</p>
                    <p><strong>位置:</strong> {{ scope.row.spotInfo.location }}</p>
                  </div>
                </template>
                <template #reference>
                  <el-tag type="info">查看详情</el-tag>
                </template>
              </el-popover>
              <el-tag v-else type="info">加载中...</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="开始时间">
            <template #default="scope">
              {{ formatDateTime(scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column label="结束时间">
            <template #default="scope">
              {{ formatDateTime(scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                type="danger" 
                size="small" 
                @click="handleCancelReservation(scope.row)"
                :disabled="scope.row.status === '已取消'"
              >
                取消预约
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="reservationsCurrentPage"
            :page-size="reservationsPageSize"
            :total="myReservations.length"
            layout="prev, pager, next, jumper"
            @current-change="handleReservationsPageChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 预约对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="预约车位"
      width="500px"
    >
      <el-form :model="reservationForm" ref="formRef" :rules="rules" label-width="100px">
        <el-form-item label="车位编号" prop="spotId">
          <el-input v-model="reservationForm.spotId" disabled></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="reservationForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DDTHH:mm:ss"
            :disabled-date="disabledDate"
            :shortcuts="dateShortcuts"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="reservationForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DDTHH:mm:ss"
            :disabled-date="disabledDate"
            :shortcuts="dateShortcuts"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReservation" :loading="submitLoading">
            确认预约
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { Van, Tickets, Bell, Refresh } from '@element-plus/icons-vue'
import { 
  selectParking, 
  selectParkingByStatus, 
  selectParkingById, 
  createReservation, 
  cancelReservation,
  selectReservationByUserId 
} from '@/api/api'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据状态
const loading = ref(false)
const reservationsLoading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const formRef = ref(null)
const spotFilter = ref('all')
const allSpots = ref([])
const availableSpots = ref([])
const myReservations = ref([])

// 预约表单
const reservationForm = reactive({
  spotId: '',
  userId: JSON.parse(localStorage.getItem('userInfo'))?.userId || '11',
  startTime: '',
  endTime: ''
})

// 日期快捷选项
const dateShortcuts = [
  { text: '今天', value: () => new Date() },
  { 
    text: '明天', 
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24)
      return date
    }
  },
  { 
    text: '一周后', 
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
      return date
    }
  }
]

// 表单验证规则
const rules = {
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (value && reservationForm.startTime && new Date(value) <= new Date(reservationForm.startTime)) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 计算属性：根据筛选条件显示车位
const filteredSpots = computed(() => {
  return spotFilter.value === 'available' ? availableSpots.value : allSpots.value
})

// 计算属性：分页车位
const paginatedSpots = computed(() => {
  const start = (spotsCurrentPage.value - 1) * spotsPageSize.value
  const end = start + spotsPageSize.value
  return filteredSpots.value.slice(start, end)
})

// 分页状态
const spotsCurrentPage = ref(1)
const spotsPageSize = ref(10)

// 计算属性：分页预约记录
const paginatedReservations = computed(() => {
  const start = (reservationsCurrentPage.value - 1) * reservationsPageSize.value
  const end = start + reservationsPageSize.value
  return myReservations.value.slice(start, end)
})

// 预约记录分页状态
const reservationsCurrentPage = ref(1)
const reservationsPageSize = ref(10)

// 方法：禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 方法：格式化日期时间
const formatDateTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '未知时间'
}

// 方法：显示预约对话框
const showReservationDialog = (spot) => {
  reservationForm.spotId = spot.spotId
  reservationForm.startTime = ''
  reservationForm.endTime = ''
  dialogVisible.value = true
}

// 方法：获取所有车位
const fetchAllSpots = async () => {
  loading.value = true
  try {
    const res = await selectParking()
    if (res.code === 200) {
      allSpots.value = res.data || []
      spotsCurrentPage.value = 1
    }
  } catch (error) {
    console.error('获取车位失败:', error)
  } finally {
    loading.value = false
  }
}

// 方法：获取可用车位
const fetchAvailableSpots = async () => {
  loading.value = true
  try {
    const res = await selectParkingByStatus()
    if (res.code === 200) {
      availableSpots.value = res.data || []
      spotsCurrentPage.value = 1
    }
  } catch (error) {
    console.error('获取可用车位失败:', error)
  } finally {
    loading.value = false
  }
}

// 方法：获取我的预约记录
const fetchMyReservations = async () => {
  reservationsLoading.value = true
  try {
    const userId = JSON.parse(localStorage.getItem('userInfo'))?.userId || '11'
    const res = await selectReservationByUserId({ userId })
    if (res.code === 200) {
      myReservations.value = res.data || []
      reservationsCurrentPage.value = 1
      if (myReservations.value.length > 0) {
        await Promise.all(myReservations.value.map(async (reservation) => {
          try {
            const spotRes = await selectParkingById({ spotId: reservation.spotId })
            if (spotRes.code === 200) {
              reservation.spotInfo = spotRes.data
            }
          } catch (error) {
            console.error(`获取车位${reservation.spotId}详情失败:`, error)
          }
        }))
      }
    }
  } catch (error) {
    console.error('获取预约记录失败:', error)
    myReservations.value = []
  } finally {
    reservationsLoading.value = false
  }
}

// 方法：提交预约
const submitReservation = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const res = await createReservation({
          spotId: reservationForm.spotId,
          userId: reservationForm.userId,
          startTime: reservationForm.startTime,
          endTime: reservationForm.endTime
        })
        if (res.code === 200) {
          ElMessage.success('车位预约成功') // 添加成功提示
          dialogVisible.value = false
          // 重新查询所有车位和用户预约信息
          await Promise.all([fetchAllSpots(), fetchAvailableSpots(), fetchMyReservations()])
        } else {
          ElMessage.error(res.msg || '预约失败')
        }
      } catch (error) {
        console.error('预约失败:', error)
        ElMessage.error('预约失败，请稍后重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 方法：取消预约
const handleCancelReservation = async (reservation) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消此预约吗？此操作不可撤销。',
      '取消确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    reservationsLoading.value = true
    const res = await cancelReservation({
      reservationId: reservation.reservationId,
      spotId: reservation.spotId,
      userId: JSON.parse(localStorage.getItem('userInfo'))?.userId
    })

    if (res.code === 200) {
      ElMessage.success('预约已成功取消')
      await Promise.all([fetchAllSpots(), fetchAvailableSpots(), fetchMyReservations()])
    } else {
      ElMessage.error(res.msg || '取消预约失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败，请稍后重试')
    }
  } finally {
    reservationsLoading.value = false
  }
}

// 方法：获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '可用': return 'success'
    case '已占用': return 'danger'
    case '已取消': return 'info'
    default: return 'info'
  }
}

// 方法：获取状态文本
const getStatusText = (status) => {
  return status || '未知状态'
}

// 方法：处理车位列表分页变化
const handleSpotsPageChange = (page) => {
  spotsCurrentPage.value = page
}

// 方法：处理预约记录分页变化
const handleReservationsPageChange = (page) => {
  reservationsCurrentPage.value = page
}

// 监听筛选条件变化
watch(spotFilter, () => {
  spotsCurrentPage.value = 1
})

// 初始化
onMounted(async () => {
  await Promise.all([fetchAllSpots(), fetchAvailableSpots(), fetchMyReservations()])
})
</script>

<style scoped>
.parking-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.overview-section {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.overview-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s;
}

.overview-card:hover {
  transform: translateY(-5px);
}

.overview-card.available {
  background: linear-gradient(135deg, #67C23A 0%, #95D475 100%);
  color: white;
}

.overview-card.my-bookings {
  background: linear-gradient(135deg, #409EFF 0%, #79BBFF 100%);
  color: white;
}

.overview-card.notice {
  background: linear-gradient(135deg, #E6A23C 0%, #F3D19E 100%);
  color: white;
}

.overview-icon {
  font-size: 32px;
  margin-right: 20px;
}

.overview-content {
  flex: 1;
}

.overview-title {
  font-size: 16px;
  margin-bottom: 8px;
}

.overview-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 4px;
}

.overview-desc {
  font-size: 14px;
  opacity: 0.9;
}

.parking-spots-section,
.my-bookings-section {
  margin-bottom: 30px;
}

.spots-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

@media (max-width: 768px) {
  .overview-section {
    grid-template-columns: 1fr;
  }

  .el-button-group {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
}

::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #909399;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: #F5F7FA;
}
</style>